class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if (head == nullptr || head->next == nullptr)
            return head;
        ListNode* newhead = new ListNode(0);
        newhead->next = head;
        ListNode *prev = newhead, *cur = prev->next, *next = cur->next,
                 *nnext = next->next;
        while (cur && next) {
            prev->next = next;
            next->next = cur;
            cur->next = nnext;

            prev = cur;
            cur = prev->next;
            if (cur)
                next = cur->next;
            if (next)
                nnext = next->next;
        }

        ListNode* ret = newhead->next;
        delete newhead;
        return ret;
    }
};